﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FIFP.Common;
using Telerik.Windows.Controls.ScheduleView;
using System.Collections.ObjectModel;
using Telerik.Windows.Controls;
using FIFP.DashBoard.Model;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using FIFP.DashBoard.Helper;
using System.Windows.Browser;
using FIFP.DashBoard.Views;
using FIFP.DashBoard.Converters;

namespace FIFP.DashBoard.ViewModel
{
    public class AppointmentVM : ViewModelCore
    {
        #region Variables
        private List<FIFPAppointment> appointments;
        private List<FIFPAppointment> filteredAppointments;
        private List<ResourceType> resourceTypes;
        private List<ResourceGroupDescription> groupTypes;
        private List<Resource> unitList;
        private bool isEditAppointment;
        private int visibleDays = 365;
        private Visibility navigationVisibility = Visibility.Collapsed;
        private string timerulerGroupStringLableFormat;
        private FixedTickProvider minorTickLength;
        private FixedTickProvider majorTickLength;
        private FixedTickProvider groupTickLength;
        public DateTime currentDate = new DateTime(DateTime.Now.Year, 1, 1);
        RadialSwitchPopup popup;
        RadScheduleView scheduleView;
        AutoInjectionPopup injectionPopup;
        DeleteAppointmentPopup deletePopup;
        RadSlider radSlider;
        #endregion

        #region Properties
        public List<FIFPAppointment> Appointments
        {
            get { return appointments; }
            set
            {
                if (appointments != value)
                {
                    appointments = value;
                    OnPropertyChanged(() => this.Appointments);
                }
            }
        }

        public List<FIFPAppointment> FilteredAppointments
        {
            get { return filteredAppointments; }
            set
            {
                if (filteredAppointments != value)
                {
                    filteredAppointments = value;
                    //this.OnPropertyChanged("FilteredAppointments");
                    OnPropertyChanged(() => this.FilteredAppointments);
                }
            }
        }

        public List<ResourceType> ResourceTypes
        {
            get { return resourceTypes; }
            set
            {
                if (resourceTypes != value)
                {
                    resourceTypes = value;
                    OnPropertyChanged(() => this.ResourceTypes);
                }
            }
        }

        public List<ResourceGroupDescription> GroupTypes
        {
            get { return groupTypes; }
            set
            {
                if (groupTypes != value)
                {
                    groupTypes = value;
                    OnPropertyChanged(() => this.GroupTypes);
                }
            }
        }

        public List<Resource> UnitList
        {
            get { return unitList; }
            set
            {
                if (unitList != value)
                {
                    unitList = value;
                    OnPropertyChanged(() => this.UnitList);
                }
            }
        }


        public bool IsEditAppointment
        {
            get { return isEditAppointment; }
            set
            {
                if (isEditAppointment != value)
                {
                    isEditAppointment = value;
                    OnPropertyChanged(() => this.IsEditAppointment);
                }
            }
        }

        public int VisibleDays
        {
            get { return visibleDays; }
            set
            {
                if (visibleDays != value)
                {
                    visibleDays = value;
                    OnPropertyChanged(() => this.VisibleDays);
                }
            }
        }


        public Visibility NavigationVisibility
        {
            get { return navigationVisibility; }
            set
            {
                if (navigationVisibility != value)
                {
                    navigationVisibility = value;
                    OnPropertyChanged(() => this.NavigationVisibility);
                }
            }
        }



        public string TimerulerGroupStringLableFormat
        {
            get { return timerulerGroupStringLableFormat; }
            set
            {
                if (timerulerGroupStringLableFormat != value)
                {
                    timerulerGroupStringLableFormat = value;
                    OnPropertyChanged(() => this.TimerulerGroupStringLableFormat);
                }
            }
        }

        public FixedTickProvider MinorTickLength
        {
            get { return minorTickLength; }
            set
            {
                if (minorTickLength != value)
                {
                    minorTickLength = value;
                    OnPropertyChanged(() => this.MinorTickLength);
                }
            }
        }

        public FixedTickProvider MajorTickLength
        {
            get { return majorTickLength; }
            set
            {
                if (majorTickLength != value)
                {
                    majorTickLength = value;
                    OnPropertyChanged(() => this.MajorTickLength);
                }
            }
        }

        public FixedTickProvider GroupTickLength
        {
            get { return groupTickLength; }
            set
            {
                if (groupTickLength != value)
                {
                    groupTickLength = value;
                    OnPropertyChanged(() => this.GroupTickLength);
                }
            }
        }

        private ObservableCollection<OverlapGroup> overlapGroups;
        public ObservableCollection<OverlapGroup> OverlapGroups
        {
            get { return overlapGroups; }
            set { SetPropertyValue(() => OverlapGroups, value, val => overlapGroups = val); }
        }

        public DateTime CurrentDate
        {
            get { return currentDate; }
            set { SetPropertyValue(() => CurrentDate, value, val => currentDate = val); }
        }

        private GroupDescriptionCollection resourceGroupTypes;
        public GroupDescriptionCollection ResourceGroupTypes
        {
            get { return resourceGroupTypes; }
            set { SetPropertyValue(() => ResourceGroupTypes, value, val => resourceGroupTypes = val); }
        }

        private ScheduleViewDragDropBehavior radScheduleViewDragDropBehavior = new ScheduleDragDropBehavior();
        public ScheduleViewDragDropBehavior RadScheduleViewDragDropBehavior
        {
            get { return radScheduleViewDragDropBehavior; }
            set { SetPropertyValue(() => RadScheduleViewDragDropBehavior, value, val => radScheduleViewDragDropBehavior = val); }
        }

        private Unit upperLevelUnit;
        public Unit UpperLevelUnit
        {
            get { return upperLevelUnit; }
            set { SetPropertyValue(() => UpperLevelUnit, value, val => upperLevelUnit = val); }
        }

        private Visibility scheduleViewVisibility = Visibility.Collapsed;
        public Visibility ScheduleViewVisibility
        {
            get { return scheduleViewVisibility; }
            set
            {
                if (scheduleViewVisibility != value)
                {
                    scheduleViewVisibility = value;
                    OnPropertyChanged(() => this.ScheduleViewVisibility);
                }
            }
        }

        private List<RadialSwitch> radialSwitchList = new List<RadialSwitch>();
        public List<RadialSwitch> RadialSwitchList
        {
            get { return radialSwitchList; }
            set { SetPropertyValue(() => RadialSwitchList, value, val => radialSwitchList = val); }
        }

        private List<int> childUnitList = new List<int>();
        public List<int> ChildUnitList
        {
            get { return childUnitList; }
            set { SetPropertyValue(() => ChildUnitList, value, val => childUnitList = val); }
        }

        private List<Unit> unitNameList = new List<Unit>();
        public List<Unit> UnitNameList
        {
            get { return unitNameList; }
            set { SetPropertyValue(() => UnitNameList, value, val => unitNameList = val); }
        }

        private DateTime rCParentStartDate;
        public DateTime RCParentStartDate
        {
            get { return rCParentStartDate; }
            set { SetPropertyValue(() => RCParentStartDate, value, val => rCParentStartDate = val); }
        }

        private DateTime rCParentEndDate;
        public DateTime RCParentEndDate
        {
            get { return rCParentEndDate; }
            set { SetPropertyValue(() => RCParentEndDate, value, val => rCParentEndDate = val); }
        }

        private double minTimeRulerExtentValue = 1500;
        public double MinTimeRulerExtentValue
        {
            get { return minTimeRulerExtentValue; }
            set
            {
                if (minTimeRulerExtentValue != value)
                {
                    minTimeRulerExtentValue = value;
                    this.OnPropertyChanged("MinTimeRulerExtentValue");
                }
            }
            //set { SetPropertyValue(() => MinTimeRulerExtentValue, value, val => minTimeRulerExtentValue = val); }
        }

        private bool bInitialLoading = true;
        public bool BInitialLoading
        {
            get { return bInitialLoading; }
            set { SetPropertyValue(() => BInitialLoading, value, val => bInitialLoading = val); }
        }


        #endregion

        #region Commands

        private ICommand _DialogCommand;
        public ICommand DialogCommand
        {
            get
            {
                return _DialogCommand ??
                        (_DialogCommand = new RelayCommand<object>(ShowAppointmentDialog));
            }
        }

        private ICommand _AppointmentCreateCommand;
        public ICommand AppointmentCreateCommand
        {
            get
            {
                return _AppointmentCreateCommand ??
                        (_AppointmentCreateCommand = new RelayCommand<object>(AppointmentCreating));
            }
        }

        private ICommand _AppointmentEditingCommand;
        public ICommand AppointmentEditingCommand
        {
            get
            {
                return _AppointmentEditingCommand ??
                        (_AppointmentEditingCommand = new RelayCommand<object>(EditAppointment));
            }
        }

        private ICommand _AppointmentEditCommand;
        public ICommand AppointmentEditCommand
        {
            get
            {
                return _AppointmentEditCommand ??
                        (_AppointmentEditCommand = new RelayCommand<object>(SaveAppointment));
            }
        }

        private ICommand _AppointmentDeletingCommand;
        public ICommand AppointmentDeletingCommand
        {
            get
            {
                return _AppointmentDeletingCommand ??
                        (_AppointmentDeletingCommand = new RelayCommand<object>(DeletingAppointment));
            }
        }
        private ICommand _AppointmentDeleteCommand;
        public ICommand AppointmentDeleteCommand
        {
            get
            {
                return _AppointmentDeleteCommand ??
                        (_AppointmentDeleteCommand = new RelayCommand<object>(DeleteAppointment));
            }
        }

        private ICommand _GroupTypeResourceLoadCommand;
        public ICommand GroupTypeResourceLoadCommand
        {
            get
            {
                return _GroupTypeResourceLoadCommand ??
                        (_GroupTypeResourceLoadCommand = new RelayCommand<RadScheduleView>(MakeResourceGroups));
            }
        }

        private ICommand _AppointmentSelectionChangedCommand;
        public ICommand AppointmentSelectionChangedCommand
        {
            get
            {
                return _AppointmentSelectionChangedCommand ??
                        (_AppointmentSelectionChangedCommand = new RelayCommand<RadScheduleView>(AppointmentSelectionChanged));
            }
        }

        private ICommand _RadialSwitchOKCommand;
        public ICommand RadialSwitchOKCommand
        {
            get
            {
                return _RadialSwitchOKCommand ??
                        (_RadialSwitchOKCommand = new RelayCommand<Button>(InsertRadialSwitchToDB));
            }
        }

        private ICommand _CancelCommand;
        public ICommand CancelCommand
        {
            get
            {
                return _CancelCommand ??
                        (_CancelCommand = new RelayCommand<Button>(HidePopup));
            }
        }

        private ICommand _InjectionCancelCommand;
        public ICommand InjectionCancelCommand
        {
            get
            {
                return _InjectionCancelCommand ??
                        (_InjectionCancelCommand = new RelayCommand<Button>(HideInjectionPopup));
            }
        }

        private ICommand _DeleteCancelCommand;
        public ICommand DeleteCancelCommand
        {
            get
            {
                return _DeleteCancelCommand ??
                        (_DeleteCancelCommand = new RelayCommand<Button>(HideDeletePopup));
            }
        }

        private ICommand _AutoInjectionCommand;
        public ICommand AutoInjectionCommand
        {
            get
            {
                return _AutoInjectionCommand ??
                        (_AutoInjectionCommand = new RelayCommand<Button>(MakeAutoInjectionTower));
            }
        }

        private ICommand _DeleteAppointmentPopupCommand;
        public ICommand DeleteAppointmentPopupCommand
        {
            get
            {
                return _DeleteAppointmentPopupCommand ??
                        (_DeleteAppointmentPopupCommand = new RelayCommand<Button>(ManualAppointmentDelete));
            }
        }

        private ICommand _RadSliderLoadCommand;
        public ICommand RadSliderLoadCommand
        {
            get
            {
                return _RadSliderLoadCommand ??
                        (_RadSliderLoadCommand = new RelayCommand<RadSlider>(LoadSliderControl));
            }
        }


        #endregion

        #region Constructor
        public AppointmentVM()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                //VisibleDays = Convert.ToInt32(new DateTime(DateTime.Now.Year,12,31).Subtract(new DateTime(DateTime.Now.Year,1,1)).TotalDays);
                ServiceLocator.Get<ImportVM>().OnAppointmentDataCompleted += new EventHandler<CustomEventArgs<AppointmentGroup>>(AppointmentVM_OnAppointmentDataCompleted);
                ServiceLocator.Get<OverlapVM>().OnAppointmentDataCompleted += new EventHandler<CustomEventArgs<AppointmentGroup>>(AppointmentVM_OnAppointmentDataCompleted);
                ServiceLocator.Get<OptMngVM>().OnAppointmentDataCompleted += new EventHandler<CustomEventArgs<AppointmentGroup>>(AppointmentVM_OnAppointmentDataCompleted);
                ServiceLocator.Get<ShutdownMngVM>().OnAppointmentDataCompleted += new EventHandler<CustomEventArgs<AppointmentGroup>>(AppointmentVM_OnAppointmentDataCompleted);
                ServiceLocator.Get<FilterVM>().OnAppointmentDataCompleted += new EventHandler<CustomEventArgs<AppointmentGroup>>(AppointmentVM_OnAppointmentDataCompleted);
                ServiceLocator.Get<OverlapVM_New>().OnAppointmentDataCompleted += new EventHandler<CustomEventArgs<AppointmentGroup>>(AppointmentVM_OnAppointmentDataCompleted);
                ServiceLocator.Get<ImportVM>().OnUnitNameListDataCompleted += new EventHandler(AppointmentVM_OnUnitNameListDataCompleted);
            }
        }

        void AppointmentVM_OnUnitNameListDataCompleted(object sender, EventArgs e)
        {
            UnitNameList = ServiceLocator.Get<ImportVM>().UnitList;
        }

        void AppointmentVM_OnAppointmentDataCompleted(object sender, CustomEventArgs<AppointmentGroup> e)
        {
            if (e.Item != null)
            {
                Appointments = e.Item.Appointments;
                InitializeScheduleViewData();
                ScheduleViewVisibility = Visibility.Visible;
                FilteredAppointments = e.Item.Appointments;
                ResourceTypes = e.Item.ResourceTypes;
                UnitList = e.Item.UnitList;
            }
        }


        private void MakeResourceGroups(RadScheduleView radView)
        {
            scheduleView = radView;
            List<ResourceGroupDescription> result = new List<ResourceGroupDescription>();
            ResourceGroupDescription group1 = new ResourceGroupDescription();
            group1.ResourceType = "Unit";
            group1.ShowNullGroup = false;
            result.Add(group1);
            radView.GroupDescriptionsSource = result;
        }

        private void LoadSliderControl(RadSlider slider)
        {
            radSlider = slider;
        }

        private void InitializeScheduleViewData()
        {

            DateTime startDate = ServiceLocator.Get<FilterVM>().StartDate;
            DateTime endDate = ServiceLocator.Get<FilterVM>().EndDate;
            DateTime actualStartDate = new DateTime(startDate.Year, startDate.Month, 1);
            DateTime actualEndDate = new DateTime(endDate.Year, endDate.Month, DateTime.DaysInMonth(endDate.Year, endDate.Month));
            CurrentDate = actualStartDate;
            if (ServiceLocator.Get<FilterVM>().StartDate == ServiceLocator.Get<FilterVM>().EndDate)
                VisibleDays = 1;
            else
                VisibleDays = Convert.ToInt32(actualEndDate.Subtract(actualStartDate).TotalDays);

            // Since we should show all the future year plans in schedule view active view definition
            if (BInitialLoading)
                BInitialLoading = false;
            else
            {

                if (ServiceLocator.Get<MainPageVM>().IsImportChecked)
                {
                    if ((Appointments != null && Appointments.Count == 0) || (Appointments.Count == 1 && Appointments[0].Subject == "ADMA"))
                        MinTimeRulerExtentValue = 1500;
                    else
                        MinTimeRulerExtentValue = 1500 - 160;
                    scheduleView.ActiveViewDefinition.MinTimeRulerExtent = MinTimeRulerExtentValue;
                    radSlider.Minimum = radSlider.Value = MinTimeRulerExtentValue;
                }
                else
                {
                    if ((Appointments != null && Appointments.Count == 0) || (Appointments.Count == 1 && Appointments[0].Subject == "ADMA"))
                        MinTimeRulerExtentValue = 1910;
                    else
                        MinTimeRulerExtentValue = 1910 - 160;
                    scheduleView.ActiveViewDefinition.MinTimeRulerExtent = MinTimeRulerExtentValue;
                    radSlider.Minimum = MinTimeRulerExtentValue;
                }
            }

            this.MinorTickLength = new FixedTickProvider(new DateTimeInterval(0, 0, 1, 0));
            this.MajorTickLength = new FixedTickProvider(new DateTimeInterval(0, 0, 1, 0));
            this.GroupTickLength = new FixedTickProvider(new DateTimeInterval(0, 0, 1, 0));
            this.TimerulerGroupStringLableFormat = "{0:MMM,yyyy}";//{0:MM/dd}
        }

        private void HideInjectionPopup(Button btnCancel)
        {
            if (injectionPopup != null && injectionPopup.Tag != null)
            {
                /*FIFPAppointment appointment = injectionPopup.Tag as FIFPAppointment;
                if (appointment != null)
                {
                    deletePopup = new DeleteAppointmentPopup();
                    deletePopup.Tag = appointment;
                    deletePopup.Closed += new EventHandler(deletePopup_Closed);
                    deletePopup.Show();
                }*/
                injectionPopup.Close();
            }
        }
        private void HideDeletePopup(Button btnCancel)
        {
            if (deletePopup != null)
                deletePopup.Close();
        }

        private void HidePopup(Button btnCancel)
        {
            if (popup != null && popup.Tag != null)
            {
                FIFPAppointment appointment = popup.Tag as FIFPAppointment;
                if (appointment != null && string.IsNullOrEmpty(appointment.LsdReason))
                {
                    deletePopup = new DeleteAppointmentPopup();
                    deletePopup.Tag = appointment;
                    deletePopup.Closed += new EventHandler(deletePopup_Closed);
                    deletePopup.Show();
                }
                popup.Close();
            }
        }

        void deletePopup_Closed(object sender, EventArgs e)
        {

        }

        private void ManualAppointmentDelete(Button btnDelete)
        {
            if (deletePopup != null && deletePopup.Tag != null)
            {
                FIFPAppointment appointment = deletePopup.Tag as FIFPAppointment;
                if (appointment != null)
                {
                    DeleteLSDPlan(appointment);
                    List<FIFPAppointment> latestAppointments = FilteredAppointments;
                    latestAppointments.Remove(appointment);
                    LoadTimelineView(latestAppointments);
                }
            }
            deletePopup.Close();
        }


        #region LoadTimelineView
        private void LoadTimelineView(List<FIFPAppointment> plans)
        {
            List<ResourceType> lstResources = new List<ResourceType>();
            List<Resource> unitList = new List<Resource>();
            ResourceType unitType = new ResourceType("Unit");
            unitType.DisplayName = "Unit";
            unitType.Name = "Unit";

            foreach (FIFPAppointment appointment in plans)
            {
                Resource resource = new Resource() { ResourceName = appointment.UnitName, DisplayName = appointment.UnitName, ResourceType = unitType.Name };
                //unitList.Add(resource);
                if (!unitList.Contains(resource))
                {
                    unitList.Add(resource);
                }
                appointment.Resources.Add(resource);
            }
            unitType.Resources.AddRange(unitList);
            lstResources.Add(unitType);

            ScheduleViewVisibility = Visibility.Visible;
            Appointments = plans;
            FilteredAppointments = plans;
            ResourceTypes = lstResources;
            UnitList = unitList;
        }
        #endregion


        #region AutoInjection
        private void MakeAutoInjectionTower(Button btnAuto)
        {
            if (injectionPopup != null && injectionPopup.Tag != null)
            {
                FIFPAppointment appointment = injectionPopup.Tag as FIFPAppointment;
                if (appointment != null)
                {
                    List<FIFPAppointment> latestAppointments = FilteredAppointments;
                    latestAppointments.Remove(appointment);
                    LoadTimelineView(latestAppointments);
                    if (injectionPopup != null)
                        injectionPopup.Close();
                    DeleteLSDPlan(appointment);
                }
            }
        }
        #endregion

        private void InsertRadialSwitchToDB(Button btnAdd)
        {
            if (popup != null && popup.Tag != null)
            {
                FIFPAppointment appointment = popup.Tag as FIFPAppointment;
                if (appointment != null && string.IsNullOrEmpty(appointment.LsdReason))
                {
                    RadialSwitch radialSwitch = new RadialSwitch();
                    radialSwitch.ScenarioId = ServiceLocator.Get<ImportVM>().CurrentScenarioId;
                    radialSwitch.UnitId = appointment.UnitID;
                    if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.UnitType == FIFPConstants.UNITTYPE_PLATFORM)//USOSSP
                        radialSwitch.ParentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId;
                    else
                        radialSwitch.ParentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.OCCPUnitId;//ByPass
                    radialSwitch.StartDate = ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.Start;
                    radialSwitch.EndDate = ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.End;
                    bool isDuplicate = false;
                    foreach (RadialSwitch rswitch in RadialSwitchList)
                    {
                        if (rswitch.UnitId == radialSwitch.UnitId && rswitch.StartDate == radialSwitch.StartDate && rswitch.EndDate == radialSwitch.EndDate)
                        {
                            radialSwitch.ParentUnitId = rswitch.ParentUnitId;
                            isDuplicate = true;
                        }
                    }
                    if (isDuplicate == false)
                        RadialSwitchList.Add(radialSwitch);
                    DeleteLSDPlanForUSOSSP(appointment);
                    List<FIFPAppointment> latestAppointments = FilteredAppointments;
                    latestAppointments.Remove(appointment);
                    LoadTimelineView(latestAppointments);
                    if (popup != null)
                        popup.Close();
                }
                else if (appointment != null && !string.IsNullOrEmpty(appointment.LsdReason) && (appointment.LsdReason == "Rerouted to ByPass" || appointment.LsdReason == "Rerouted to USOSSP"))
                {
                    int parentUnitId;
                    FIFPAppointment activity = ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans.Where(s => s.PlanID == appointment.LSDParentActivityPlanId).FirstOrDefault();
                    if (appointment != null)
                    {
                        if (appointment.LsdReason == "Rerouted to ByPass")
                            parentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId;
                        else
                            parentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.OCCPUnitId;
                        RadialSwitch radialSwitch = null;
                        foreach (RadialSwitch radial in ServiceLocator.Get<AppointmentVM>().RadialSwitchList)
                        {
                            if (radial.UnitId == appointment.UnitID && radial.ParentUnitId == parentUnitId && radial.StartDate == appointment.OriginalStart && radial.EndDate == appointment.OriginalEnd)
                                radialSwitch = radial;
                        }
                        if (radialSwitch != null)
                            ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Remove(radialSwitch);
                        else
                        {
                            #region If we revert db radial switch we have to remove it from db radial list
                            RadialSwitch dbRadialSwitch = null;
                            foreach (RadialSwitch radial in ServiceLocator.Get<ImportVM>().RadialSwitchListFromDB)
                            {
                                if (radial.UnitId == appointment.UnitID && radial.ParentUnitId == parentUnitId && radial.StartDate == appointment.OriginalStart && radial.EndDate == appointment.OriginalEnd)
                                    dbRadialSwitch = radial;
                            }
                            #endregion

                            if (dbRadialSwitch != null)
                                ServiceLocator.Get<ImportVM>().RadialSwitchListFromDB.Remove(dbRadialSwitch);

                            radialSwitch = new RadialSwitch();
                            radialSwitch.IsRevert = true;
                            radialSwitch.ScenarioId = ServiceLocator.Get<ImportVM>().CurrentScenarioId;
                            radialSwitch.UnitId = appointment.UnitID;
                            if (appointment.LsdReason == "Rerouted to ByPass")
                                radialSwitch.ParentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.OCCPUnitId;
                            else
                                radialSwitch.ParentUnitId = ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId;
                            radialSwitch.StartDate = appointment.Start;
                            radialSwitch.EndDate = appointment.End;
                            ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Add(radialSwitch);
                        }

                        RemoveRadialSwitchLSD(appointment);

                        List<int> lsdIds = ServiceLocator.Get<ShutdownMngVM>().ModifiedLinkedShutdownList.Where(f => f.UnitID != appointment.UnitID).Select(p => p.UnitID).ToList<int>();
                        string Ids = string.Join(",", lsdIds);
                        activity.LSDDeletedIds = Ids;

                        activity.IsDefaultUnitShutdown = false;//For selected activity we no need to set isLinkedShutdown=false just set IsOpen = true
                        ActivityType activityCode = ServiceLocator.Get<ImportVM>().ActivityCodeDivisionList.Where(s => s.Name == activity.ActivityCode && s.ActivityStatus == "Open").FirstOrDefault();
                        if (activityCode != null && activity.UnitStatus != "Open")
                        {
                            activity.UnitStatus = activityCode.ActivityStatus;
                            activity.ActivityId = activityCode.Id;
                        }

                        //Clear child units suppose if it has items
                        if (ChildUnitList != null && ChildUnitList.Count > 0)
                            ChildUnitList.Clear();

                        ChildUnitList.Add(appointment.UnitID);
                        if (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER)
                        {
                            GetTowerChildUnits(appointment.UnitID);
                        }
                        else
                        {
                            GetChildUnitNameList(UnitNameList.Where(s => s.ParentUnitID == appointment.UnitID).ToList<Unit>());
                        }
                        ChildUnitList = ChildUnitList.Distinct().ToList<int>();//This child includes the the selected activity wells and strings and also the linked shutdown units
                        activity.LsdPlans.Where(p => ChildUnitList.Any(q => q.Equals(p.UnitID))).ToList<FIFPAppointment>().ForEach(s => { s.IsLinkedShutdownPlan = true; });//This LsdPlans includes the the selected activity wells and strings and also the linked shutdown units
                        ChildUnitList = new List<int>();
                        activity.IsModified = activity.IsModified == 1 ? 1 : 0;
                        appointment.LsdReason = string.Empty;
                        ServiceLocator.Get<ShutdownMngVM>().ModifiedLinkedShutdownList = new ObservableCollection<FIFPAppointment>(ServiceLocator.Get<ShutdownMngVM>().ModifiedLinkedShutdownList.Where(f => f.UnitID != appointment.UnitID));

                        appointment.IsLinkedShutdownPlan = true;
                        appointment.LsdReason = string.Empty;

                        List<FIFPAppointment> latestAppointments = FilteredAppointments;
                        latestAppointments.Remove(appointment);
                        LoadTimelineView(latestAppointments);
                        if (popup != null)
                            popup.Close();
                    }
                }
            }
        }

        private void RemoveRadialSwitchLSD(FIFPAppointment ModifiedSelectedActivity)
        {
            List<FIFPAppointment> Plans = new List<FIFPAppointment>();
            if (ModifiedSelectedActivity.LsdReason == "Rerouted to ByPass")//OCCP
            {
                Plans = ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans.Where(s => s.UnitID == ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId).ToList<FIFPAppointment>();
            }
            else
            {
                Plans = ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans.Where(s => s.UnitID == ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.USOSSPUnitId).ToList<FIFPAppointment>();
            }

            foreach (FIFPAppointment plan in Plans)
            {
                bool overlap = !(plan.End < ModifiedSelectedActivity.Start || plan.Start > ModifiedSelectedActivity.End);
                if (overlap)
                {
                    childUnitList.Add(ModifiedSelectedActivity.UnitID);
                    GetChildUnitNameList(UnitNameList.Where(s => s.ParentUnitID == ModifiedSelectedActivity.UnitID).ToList<Unit>());
                    plan.LsdPlans.RemoveAll(s => childUnitList.Any(p => p.Equals(s.UnitID)) && s.IsRadialSwitch == true);
                }
                if (ModifiedSelectedActivity.LsdReason == "Rerouted to USOSSP")//Remove the bypass radial from USOSSP radial list
                {
                    if (ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Contains(ModifiedSelectedActivity.UnitID))
                        ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Remove(ModifiedSelectedActivity.UnitID);
                }
            }
        }

        private void ShowAppointmentDialog(object e)
        {
            ShowDialogEventArgs eventArgs = e as ShowDialogEventArgs;
            if (eventArgs.DialogViewModel is ConfirmDialogViewModel)
            {
                ConfirmDialogViewModel viewModel = eventArgs.DialogViewModel as ConfirmDialogViewModel;
                if (viewModel != null && viewModel.Appointments.Count() > 0)
                {
                    IOccurrence[] occurance = viewModel.Appointments as IOccurrence[];
                    if (occurance != null)
                    {
                        FIFPAppointment appointment = occurance[0] as FIFPAppointment;
                        Unit unit = ServiceLocator.Get<ShutdownMngVM>().SelectedLSDLocation;
                        if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked && unit != null && ((unit.UnitType == FIFPConstants.UNITTYPE_PLATFORM && unit.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM) || (unit.UnitType == FIFPConstants.UNITTYPE_PIPELINE && unit.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)))
                        {
                            if (appointment.IsDefaultUnitShutdown)
                                eventArgs.Cancel = true;
                            else if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity == null)
                            {
                                eventArgs.Cancel = true;
                                ShowPopup(FIFPConstants.WARNINGTITLE_SELECT_ACTIVITY, FIFPConstants.WARNINGMESSAGE_DELETE_LSD_ACTIVITY);
                            }
                            else if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity != null && (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.Start != appointment.Start && ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.End != appointment.End))
                            {
                                eventArgs.Cancel = true;
                                ShowPopup(FIFPConstants.WARNINGTITLE_DELETE_LSD_ACTIVITY, FIFPConstants.WARNINGMESSAGE_SELECT_LSD_ACTIVITY);
                            }
                            else
                            {
                                if (!appointment.IsRadialSwitch && appointment.UnitType == FIFPConstants.UNITTYPE_RADIAL && string.IsNullOrEmpty(appointment.LsdReason))
                                {
                                    eventArgs.Cancel = true;
                                    //List<FIFPAppointment> latestAppointments = FilteredAppointments;
                                    //latestAppointments.Remove(appointment);
                                    //LoadTimelineView(latestAppointments);

                                    //scheduleView.Remove(scheduleView.SelectedAppointment); 
                                    //RadScheduleViewCommands.DeleteAppointment.Execute(null, scheduleView);
                                    //if (popup == null)
                                    {
                                        popup = new RadialSwitchPopup();
                                        popup.Tag = appointment;//"Rerouted to ByPass" || plan.LsdReason == "Rerouted to USOSSP"
                                        if (unit.UnitType == FIFPConstants.UNITTYPE_PLATFORM)
                                        {
                                            popup.Title = "Switch to Bypass oil line";
                                            popup.lblMessage.Text = "Do you want to switch this radial to Bypass oil line?";
                                        }
                                        else
                                        {
                                            popup.Title = "Switch to USOSSP";
                                            popup.lblMessage.Text = "Do you want to switch this radial to USOSSP?";
                                        }

                                        popup.Closed += new EventHandler(popup_Closed);
                                        popup.Show();
                                    }
                                }
                                else if (!string.IsNullOrEmpty(appointment.LsdReason) && appointment.LsdReason == "Rerouted to ByPass" || appointment.LsdReason == "Rerouted to USOSSP")
                                {
                                    //Switch back to ByPass or USOSSP radials
                                    eventArgs.Cancel = true;

                                    popup = new RadialSwitchPopup();
                                    popup.Tag = appointment;
                                    if (unit.UnitType == FIFPConstants.UNITTYPE_PLATFORM)
                                    {
                                        popup.Title = "Switch to Bypass oil line";
                                        popup.lblMessage.Text = "Do you want to switch back this radial to Bypass oil line?";
                                    }
                                    else
                                    {
                                        popup.Title = "Switch to USOSSP";
                                        popup.lblMessage.Text = "Do you want to switch back this radial to USOSSP?";
                                    }

                                    popup.Closed += new EventHandler(popup_Closed);
                                    popup.Show();
                                }
                            }
                        }
                        else if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked && unit != null && (unit.UnitType == FIFPConstants.UNITTYPE_PLATFORM && unit.UnitName == FIFPConstants.PLATFORM_CP1_UNIT && appointment.UnitType == FIFPConstants.UNITTYPE_TOWER))
                        {
                            if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity == null)
                            {
                                eventArgs.Cancel = true;
                                ShowPopup(FIFPConstants.WARNINGTITLE_SELECT_ACTIVITY, FIFPConstants.WARNINGMESSAGE_DELETE_LSD_ACTIVITY);
                            }
                            else if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity != null && (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.Start != appointment.Start && ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.End != appointment.End))
                            {
                                eventArgs.Cancel = true;
                                ShowPopup(FIFPConstants.WARNINGTITLE_DELETE_LSD_ACTIVITY, FIFPConstants.WARNINGMESSAGE_SELECT_LSD_ACTIVITY);
                            }
                            else
                            {
                                //Handling AutoInjection
                                eventArgs.Cancel = true;
                                injectionPopup = new AutoInjectionPopup();
                                injectionPopup.Tag = appointment;
                                injectionPopup.Closed += new EventHandler(injectionPopup_Closed);
                                injectionPopup.Show();
                            }
                        }
                        else
                        {
                            // LSD Checking
                            if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked && appointment.IsLinkedShutdownPlan)//We allow user only if they click linked shutdown units
                            {
                                if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity == null)
                                {
                                    eventArgs.Cancel = true;
                                    ShowPopup(FIFPConstants.WARNINGTITLE_SELECT_ACTIVITY, FIFPConstants.WARNINGMESSAGE_DELETE_LSD_ACTIVITY);
                                }
                                //else if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity != null && ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.ActivityCode != appointment.ParentActivityCode )
                                else if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity != null && (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.Start != appointment.Start && ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.End != appointment.End))
                                {
                                    eventArgs.Cancel = true;
                                    ShowPopup(FIFPConstants.WARNINGTITLE_DELETE_LSD_ACTIVITY, FIFPConstants.WARNINGMESSAGE_SELECT_LSD_ACTIVITY);
                                }
                                else if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity != null && ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.IsDefaultUnitShutdown)
                                {
                                    //User select the activity from activity Grid

                                    if (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER && ServiceLocator.Get<ShutdownMngVM>().SelectedLSDLocation.UnitType == FIFPConstants.UNITTYPE_WELL && (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL))//Rig Activity
                                    {
                                        eventArgs.Cancel = true;//We can't delete RIG activity LSD units. We can only apply SIMOPS
                                        /*Unit defaultSDUnit = UnitNameList.Where(p => p.UnitID == ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.UnitID).FirstOrDefault();
                                        if (defaultSDUnit != null)
                                        {
                                            Unit parentUnit = UnitNameList.Where(p => p.UnitID == defaultSDUnit.ParentUnitID).FirstOrDefault();
                                            if (parentUnit != null && parentUnit.UnitName == appointment.UnitName)
                                            {
                                                eventArgs.Cancel = true;
                                            }
                                        }*/
                                    }
                                    //else if (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER && appointment.FluidType != FIFPConstants.FLUIDTYPE_GAS)//We no need to check the findparent function for Gas unit because in gas, all 3 towers are direct parent to CP1
                                    //{
                                    //    FindParentUnit(eventArgs, appointment);
                                    //}
                                }
                                else
                                {
                                    if (appointment != null && !appointment.IsAppointmentDelete)
                                        eventArgs.Cancel = true;
                                }
                            }
                            else
                            {
                                if (appointment != null && !appointment.IsAppointmentDelete && !ServiceLocator.Get<MainPageVM>().IsImportChecked)
                                    eventArgs.Cancel = true;
                            }
                        }
                    }
                }
            }
            else if (eventArgs.DialogViewModel is AppointmentDialogViewModel)
            {
                AppointmentDialogViewModel viewModel = eventArgs.DialogViewModel as AppointmentDialogViewModel;
                if (viewModel != null)
                {
                    Occurrence occurance = viewModel.Occurrence as Occurrence;
                    if (occurance != null)
                    {
                        FIFPAppointment appointment = occurance.Appointment as FIFPAppointment;
                        if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked)
                        {
                            if (appointment != null && appointment.IsAppointmentDelete && appointment.IsLinkedShutdownPlan)
                            {
                                eventArgs.Cancel = true;
                            }
                        }
                        else if (ServiceLocator.Get<MainPageVM>().IsOverLapChecked)
                        {
                            if (appointment != null && appointment.IsAppliedSimops)
                                eventArgs.Cancel = true;
                        }
                        //else if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked) //User should edit an appointment in Optimization page also.
                        //    eventArgs.Cancel = true;
                    }
                }
            }

        }

        void injectionPopup_Closed(object sender, EventArgs e)
        {
        }

        void popup_Closed(object sender, EventArgs e)
        {
        }

        private void FindParentUnit(ShowDialogEventArgs eventArgs, FIFPAppointment appointment)
        {
            Unit unit = UnitNameList.Where(s => s.UnitID == appointment.UnitID).FirstOrDefault();
            GetUnitNameList(unit);
            if (UpperLevelUnit != ServiceLocator.Get<ShutdownMngVM>().SelectedLSDLocation)
            {
                eventArgs.Cancel = true;
                ShowPopup(FIFPConstants.WARNINGTITLE_DELETE_LSD_ACTIVITY, FIFPConstants.WARNINGMESSAGE_DELETE_LSD);
            }
        }

        private void FindParentForGasUnit(ShowDialogEventArgs eventArgs, FIFPAppointment appointment)
        {
            Unit unit = UnitNameList.Where(s => s.UnitID == appointment.UnitID).FirstOrDefault();
            if (unit != null)
            {
                Unit pipelineUnit = UnitNameList.Where(p => p.UnitID == unit.ParentUnitID).FirstOrDefault();
                if (pipelineUnit != null)
                {
                    Unit rootUnit = UnitNameList.Where(p => p.UnitID == pipelineUnit.ParentUnitID).FirstOrDefault();
                    if (rootUnit != null)
                        UpperLevelUnit = rootUnit;
                }
            }

            if (UpperLevelUnit != ServiceLocator.Get<ShutdownMngVM>().SelectedLSDLocation)
            {
                eventArgs.Cancel = true;
                ShowPopup(FIFPConstants.WARNINGTITLE_DELETE_LSD_ACTIVITY, FIFPConstants.WARNINGMESSAGE_DELETE_LSD);
            }
        }

        private void GetUnitNameList(Unit unit)
        {
            Unit childUnit = UnitNameList.Where(p => p.UnitID == unit.ParentUnitID).FirstOrDefault();
            if (childUnit.UnitType != FIFPConstants.UNITTYPE_TOWER && childUnit.UnitType != FIFPConstants.UNITTYPE_RADIAL)
                GetUnitNameList(childUnit);
            else
                UpperLevelUnit = childUnit;
        }

        private void AppointmentCreating(object e)
        {

            //FIFPAppointment appointment = eventArgs.Appointment as FIFPAppointment;
            //if (appointment != null)
            //{
            //    appointment.IsDescEnabled = true;
            //}
            AppointmentCreatingEventArgs eventArgs = e as AppointmentCreatingEventArgs;
            if (eventArgs != null) //We can't create new appointment from gantt chart
                eventArgs.Cancel = true;

        }


        private void EditAppointment(object e)
        {

            if (ServiceLocator.Get<ImportVM>().IsAnimationStarted)
            {
                ServiceLocator.Get<ImportVM>().IsAnimationStarted = false;
                StoryboardManager.PlayStoryboard(FIFPConstants.SETTINGSFLIP_STOP, s => { }, null);
            }
            AppointmentEditingEventArgs eventArgs = e as AppointmentEditingEventArgs;
            FIFPAppointment appointment = eventArgs.Appointment as FIFPAppointment;

            if (appointment != null)
            {
                RCParentStartDate = appointment.Start; //This is used to check if any activiti modified we should update in reduced capacity list too.
                RCParentEndDate = appointment.End;

                appointment.ActivityLevel++;
                //appointment.Body = appointment.Division + "," + appointment.UnitType + "," + appointment.UnitName + "," + appointment.ActivityType;
                //appointment.IsSubjectEnabled = false;
                //appointment.Body = appointment.UnitName + " - " + appointment.ActivityDescription;
                if (!string.IsNullOrEmpty(appointment.Remarks))
                    appointment.Body = appointment.Remarks;
                else
                {
                    appointment.Body = appointment.UnitName + " - " + appointment.ActivityCodeDescription;
                }
                appointment.IsDescEnabled = false;
                IsEditAppointment = true;
            }


            if (appointment != null && (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked))
            {
                bool bRet = false;
                //List<RadialSwitch> tempRadialList = MergeRadialDBWithTempList();
                //if (tempRadialList != null && tempRadialList.Count > 0)
                //{
                //    foreach (RadialSwitch radialSwitch in tempRadialList)
                //    {
                //        if (radialSwitch.ParentUnitId == ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId || radialSwitch.ParentUnitId == ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.OCCPUnitId)
                //            bRet = true;
                //    }
                //}
                foreach (FIFPAppointment plan in appointment.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_RADIAL))
                {
                    if (plan.LsdReason != null && (plan.LsdReason == "Rerouted to ByPass" || plan.LsdReason == "Rerouted to USOSSP"))
                    {
                        bRet = true;
                    }
                }
                if (bRet)
                {
                    ShowPopup(FIFPConstants.WARNINGTITLE_DRAG_RADIALSWITCH, FIFPConstants.WARNINGMESSAGE_DRAG_RADIALSWITCH);
                    eventArgs.Cancel = true;
                }
            }
            else if (appointment != null && ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && appointment.IsLinkedShutdownPlan) //Time being fix for resize event for lsd plans in optimization UI. If you resize it it put an entry in modification list.
            {
                eventArgs.Cancel = true;
            }
            //This condition is no need. Will review this later
            //else
            //{
            //    if (appointment.Start == appointment.OriginalStart && appointment.End <= appointment.OriginalEnd)
            //        eventArgs.Cancel = true;
            //}

            if (appointment != null && appointment.ActivityLevel > 2)
            {

                appointment.ModifiedStart = appointment.Start;
                appointment.ModifiedEnd = appointment.End;
            }
        }
        private void SaveAppointment(object e)
        {
            AppointmentEditedEventArgs eventArgs = e as AppointmentEditedEventArgs;


            FIFPAppointment appointment = eventArgs.Appointment as FIFPAppointment;
            if (appointment != null)
            {
                if (!string.IsNullOrEmpty(appointment.DB_Remarks) && appointment.DB_Remarks.Equals(appointment.Body))
                    appointment.IsModified = -1;
                else
                    appointment.IsModified = 0;
                appointment.Remarks = appointment.Body;
                appointment.Start = new DateTime(appointment.Start.Year, appointment.Start.Month, appointment.Start.Day, 0, 0, 0);
                appointment.End = new DateTime(appointment.End.Year, appointment.End.Month, appointment.End.Day, 23, 59, 59);
                appointment.OriginalStart = new DateTime(appointment.OriginalStart.Year, appointment.OriginalStart.Month, appointment.OriginalStart.Day, 0, 0, 0);
                appointment.OriginalEnd = new DateTime(appointment.OriginalEnd.Year, appointment.OriginalEnd.Month, appointment.OriginalEnd.Day, 23, 59, 59);

                int modifiedDays = Convert.ToInt32(Math.Round(appointment.End.Subtract(appointment.Start).TotalDays));
                appointment.ModifiedTotalDays = modifiedDays > 1 ? modifiedDays.ToString() + " Days" : modifiedDays.ToString() + " Day";
                
                int originalDays = Convert.ToInt32(Math.Round(appointment.OriginalEnd.Subtract(appointment.OriginalStart).TotalDays));
                appointment.OriginalTotalDays = originalDays > 1 ? originalDays.ToString() + " Days" : originalDays.ToString() + " Day";


                SynchronizeRC(appointment);

                if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked) //This is calling twice.
                {
                    foreach (FIFPAppointment activity in ServiceLocator.Get<ShutdownMngVM>().ActivityListWithSelectedUnit)
                    {
                        if (appointment.Equals(activity))
                        {
                            foreach (FIFPAppointment lsdPlan in activity.LsdPlans) //update modified date to lsd plans
                            {
                                lsdPlan.Start = appointment.Start;
                                lsdPlan.End = appointment.End;
                            }

                            foreach (FIFPAppointment lsdPlan in activity.FilteredLsdPlans) //update modified date to filtered plans
                            {
                                lsdPlan.Start = appointment.Start;
                                lsdPlan.End = appointment.End;
                            }

                            foreach (FIFPAppointment lsdPlan in ServiceLocator.Get<ShutdownMngVM>().ModifiedLinkedShutdownList) //update modified date to modified plans
                            {
                                lsdPlan.Start = appointment.Start;
                                lsdPlan.End = appointment.End;
                            }


                            Unit unit = ServiceLocator.Get<ShutdownMngVM>().SelectedLSDLocation;//Drag and drop the activity then we have to generate the new lsd for Bypass and OCCP Radials
                            if (unit != null && ((unit.UnitType == FIFPConstants.UNITTYPE_PLATFORM && unit.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM) || (unit.UnitType == FIFPConstants.UNITTYPE_PIPELINE && unit.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)))
                            {
                                List<RadialSwitch> tempRadialList = MergeRadialDBWithTempList();
                                foreach (RadialSwitch rsAppointment in tempRadialList)
                                {
                                    bool overlap = !(activity.End < rsAppointment.StartDate || activity.Start > rsAppointment.EndDate);
                                    if (overlap)
                                    {
                                        DateTime startDate = new DateTime();
                                        DateTime endDate = new DateTime();
                                        if (activity.Start > rsAppointment.StartDate)
                                            startDate = activity.Start;
                                        else
                                            startDate = rsAppointment.StartDate;

                                        if (activity.End < rsAppointment.EndDate)
                                            endDate = activity.End;
                                        else
                                            endDate = rsAppointment.EndDate;

                                        //We have to update the new start date and end date for radial switch units
                                        foreach (FIFPAppointment lsdPlans in activity.LsdPlans.Where(s => s.UnitID == rsAppointment.UnitId))
                                        {
                                            lsdPlans.IsLinkedShutdownPlan = true;
                                            lsdPlans.Start = startDate;
                                            lsdPlans.End = endDate;
                                        }
                                    }
                                    else
                                    {
                                        //if it is not overlapped then we have to set the linked shutdown false for radial unit
                                        activity.LsdPlans.Where(s => s.UnitID == rsAppointment.UnitId).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = false; });
                                    }
                                }
                            }
                            break;
                        }
                    }

                    if (ServiceLocator.Get<ShutdownMngVM>().ActivityListWithSelectedUnit != null && ServiceLocator.Get<ShutdownMngVM>().ActivityListWithSelectedUnit.Count > 0) //If we change the appointment start date and end date we have to update the same for linked shutdown plans
                    {

                        List<FIFPAppointment> lsdPlans = new List<FIFPAppointment>();
                        foreach (FIFPAppointment activity in ServiceLocator.Get<ShutdownMngVM>().ActivityListWithSelectedUnit)
                        {
                            lsdPlans.Add(activity);
                            lsdPlans.AddRange(activity.FilteredLsdPlans.Where(s => s.IsLinkedShutdownPlan == true));
                        }
                        Dispatcher.BeginInvoke(() => { FilteredAppointments = lsdPlans; });
                        //FilteredAppointments = lsdPlans; 
                    }
                }
                if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsOptMngChecked)
                {
                    List<FIFPAppointment> lsdChilds = ServiceLocator.Get<OptMngVM>().FilteredLinkedShutdownList.Where(s => s.UnitID == appointment.UnitID && s.IsLinkedShutdownPlan == true).ToList<FIFPAppointment>();
                    if (lsdChilds != null && lsdChilds.Count > 0)
                    {
                        foreach (FIFPAppointment appointmentItem in lsdChilds)
                        {
                            bool overlap = !(appointmentItem.End < appointment.Start || appointmentItem.Start > appointment.End);
                            if (overlap)
                            {
                                appointment.OptimizedReason = "Activity optimized";
                                if (!ServiceLocator.Get<OptMngVM>().OptimizedActivityList.Contains(appointment))
                                    ServiceLocator.Get<OptMngVM>().OptimizedActivityList.Add(appointment);
                                foreach (FIFPAppointment lsdPlan in appointment.LsdPlans.Where(s => s.IsLinkedShutdownPlan == true))//If we move activity for optimize, we have to change start and end date accordingly.
                                {
                                    lsdPlan.Start = appointment.Start;
                                    lsdPlan.End = appointment.End;
                                }
                                break;
                            }
                            else
                            {
                                if (ServiceLocator.Get<OptMngVM>().OptimizedActivityList.Contains(appointment))
                                {
                                    appointment.OptimizedReason = string.Empty;
                                    ServiceLocator.Get<OptMngVM>().OptimizedActivityList = new ObservableCollection<FIFPAppointment>(ServiceLocator.Get<OptMngVM>().OptimizedActivityList.Except(new List<FIFPAppointment>() { appointment }));
                                }
                                foreach (FIFPAppointment lsdPlan in appointment.LsdPlans.Where(s => s.IsLinkedShutdownPlan == true))//If we move activity for optimize, we have to change start and end date accordingly.
                                {
                                    lsdPlan.Start = appointment.Start;
                                    lsdPlan.End = appointment.End;
                                }
                            }

                        }//TODO need to overlap checking while optimizing activities 
                        //isOverlap = !(planList[i + 1].End < planList[i].Start || planList[i + 1].Start > planList[i].End);
                    }
                }

                //if ((appointment.Start != appointment.OriginalStart || appointment.End != appointment.OriginalEnd) && appointment.IsModified != 1) //If we change the activity in gantt view, set IsModified = 0 to update into database.
                if (appointment.Start != appointment.ModifiedStart || appointment.End != appointment.ModifiedEnd) //If we change the activity in gantt view, set IsModified = 0 to update into database.
                    appointment.IsModified = appointment.IsModified == 1 ? 1 : 0;

            }
        }

        public void SynchronizeRC(FIFPAppointment appointment)
        {
            //If we move the activity in any page, we have to update the start date and end date of the activity in reduced capacity list too.
            List<ReducedCapacity> reducedCapacityList = ServiceLocator.Get<ImportVM>().GetCombinedRCList();
            if (reducedCapacityList != null && reducedCapacityList.Count > 0)
            {
                List<ReducedCapacity> capacityList = reducedCapacityList.Where(s => s.PlanId == appointment.PlanID && s.ParentUnitId == appointment.UnitID && s.StartDate == RCParentStartDate && s.EndDate == RCParentEndDate).ToList<ReducedCapacity>();
                if (capacityList != null && capacityList.Count > 0)
                    capacityList.ForEach(s => { s.StartDate = appointment.Start; s.EndDate = appointment.End; });
            }
        }

        private void DeletingAppointment(object e)
        {
        }

        private void DeleteAppointment(object e)
        {
            AppointmentDeletedEventArgs eventArgs = e as AppointmentDeletedEventArgs;
            FIFPAppointment appointment = eventArgs.Appointment as FIFPAppointment;
            DeleteLSDPlan(appointment);
        }

        private void DeleteLSDPlan(FIFPAppointment appointment)
        {
            FIFPAppointment activity = ServiceLocator.Get<ShutdownMngVM>().SelectedActivity;
            if (appointment != null && (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked) && activity != null)
            {
                appointment.IsLinkedShutdownPlan = false;
                if (activity.UnitName == FIFPConstants.PLATFORM_CP1_UNIT && appointment.UnitType == FIFPConstants.UNITTYPE_TOWER)
                {
                    appointment.LsdReason = "Switched to Auto injection"; appointment.ActivityCode = "LSD";
                }
                else
                    appointment.LsdReason = "LSD deleted"; appointment.ActivityCode = "LSD";

                ServiceLocator.Get<ShutdownMngVM>().ModifiedLinkedShutdownList.Add(appointment);
                ServiceLocator.Get<ShutdownMngVM>().FilteredLinkedShutdownList.Remove(appointment);
                if (activity != null && activity.LSDDeletedIds != null && activity.LSDDeletedIds.Length > 0 && activity.LSDDeletedIds.LastIndexOf(',') == -1)
                    activity.LSDDeletedIds = activity.LSDDeletedIds + ",";
                activity.LSDDeletedIds += appointment.UnitID + ",";
                activity.IsModified = activity.IsModified == 1 ? 1 : 0;

                //Clear child units suppose if it has items
                if (ChildUnitList != null && ChildUnitList.Count > 0)
                    ChildUnitList.Clear();

                if (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER)
                {
                    GetTowerChildUnits(appointment.UnitID);
                }
                else
                {
                    GetChildUnitNameList(UnitNameList.Where(s => s.ParentUnitID == appointment.UnitID).ToList<Unit>());
                }
                ChildUnitList = ChildUnitList.Distinct().ToList<int>();//This child includes the the selected activity wells and strings and also the linked shutdown units
                activity.LsdPlans.Where(p => ChildUnitList.Any(q => q.Equals(p.UnitID))).ToList<FIFPAppointment>().ForEach(s => { s.IsLinkedShutdownPlan = false; });//This LsdPlans includes the the selected activity wells and strings and also the linked shutdown units

                List<FIFPAppointment> deletedLsds = activity.LsdPlans.Where(s => s.IsLinkedShutdownPlan == true).ToList<FIFPAppointment>();

                activity.IsDefaultUnitShutdown = false;//For selected activity we no need to set isLinkedShutdown=false just set IsOpen = true
                ActivityType activityCode = ServiceLocator.Get<ImportVM>().ActivityCodeDivisionList.Where(s => s.Name == activity.ActivityCode && s.ActivityStatus == "Open").FirstOrDefault();
                if (activityCode != null && activity.UnitStatus != "Open")
                {
                    activity.UnitStatus = activityCode.ActivityStatus;
                    activity.ActivityId = activityCode.Id;
                }
            }
            else
            {
                ServiceLocator.Get<ImportVM>().ImportPlans.Remove(appointment);
                if (ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans != null && ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans.Count > 0 && ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans.Contains(appointment))
                    ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans.Remove(appointment);
                if (appointment.IsModified != 1) //We have to check it future bcoz linked sd activity also has the id 0
                    ServiceLocator.Get<ImportVM>().DeletedActivityIds.Add(appointment.PlanID);
            }
        }

        private void GetTowerChildUnits(int unitId)
        {
            Unit towerUnit = UnitNameList.Where(p => p.UnitID == unitId).FirstOrDefault();
            if (towerUnit != null)
            {
                Unit pipelineUnit = UnitNameList.Where(p => p.UnitID == towerUnit.ParentUnitID).FirstOrDefault();
                ChildUnitList.Add(pipelineUnit.UnitID);
                List<Unit> lstChildUnits = UnitNameList.Where(s => s.ParentUnitID == unitId).ToList<Unit>();
                lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
                ChildUnitList.AddRange(lstChildUnits.Select(s => s.UnitID).ToList<int>());
            }
        }


        private void DeleteLSDPlanForUSOSSP(FIFPAppointment appointment)
        {
            FIFPAppointment activity = ServiceLocator.Get<ShutdownMngVM>().SelectedActivity;
            if (appointment != null && (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked) && activity != null)
            {
                appointment.IsLinkedShutdownPlan = false;

                SwitchRadialForOverlappedActivities(appointment);


                appointment.ActivityCode = "LSD";
                ServiceLocator.Get<ShutdownMngVM>().ModifiedLinkedShutdownList.Add(appointment);
                ServiceLocator.Get<ShutdownMngVM>().FilteredLinkedShutdownList.Remove(appointment);
                if (activity != null && activity.LSDDeletedIds != null && activity.LSDDeletedIds.Length > 0 && activity.LSDDeletedIds.LastIndexOf(',') == -1)
                    activity.LSDDeletedIds = activity.LSDDeletedIds + ",";
                activity.LSDDeletedIds += appointment.UnitID + ",";
                activity.IsModified = activity.IsModified == 1 ? 1 : 0;

                //Clear child units suppose if it has items
                if (ChildUnitList != null && ChildUnitList.Count > 0)
                    ChildUnitList.Clear();

                GetChildUnitNameList(UnitNameList.Where(s => s.ParentUnitID == appointment.UnitID).ToList<Unit>()); //We have to make isLinkedShutdown=false to all its child
                ChildUnitList = ChildUnitList.Distinct().ToList<int>();
                activity.LsdPlans.Where(p => ChildUnitList.Any(q => q.Equals(p.UnitID))).ToList<FIFPAppointment>().ForEach(s => { s.IsLinkedShutdownPlan = false; });

            }
            else
            {

                ServiceLocator.Get<ImportVM>().ImportPlans.Remove(appointment);
                if (appointment.IsModified != 1) //We have to check it future bcoz linked sd activity also has the id 0
                    ServiceLocator.Get<ImportVM>().DeletedActivityIds.Add(appointment.PlanID);

            }
        }



        private void SwitchRadialForOverlappedActivities(FIFPAppointment appointment)
        {
            List<FIFPAppointment> Plans = new List<FIFPAppointment>();

            if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.UnitType == FIFPConstants.UNITTYPE_PLATFORM)//OCCP
            {
                appointment.LsdReason = "Rerouted to ByPass";

                Plans = ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans.Where(s => s.UnitID == ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.ByPassUnitId).ToList<FIFPAppointment>();

            }
            else
            {
                appointment.LsdReason = "Rerouted to USOSSP";
                Plans = ServiceLocator.Get<ShutdownMngVM>().ShutdownPlans.Where(s => s.UnitID == ServiceLocator.Get<ImportVM>().RadialSwitchDefaultValue.USOSSPUnitId).ToList<FIFPAppointment>();
            }

            List<RadialSwitch> radialSwitchList = MergeRadialDBWithTempList();
            //Delete the switched radial linked shutdown and regenerate it again
            List<FIFPAppointment> bforeDelete = Plans.SelectMany(s => s.LsdPlans).Where(p => p.IsRadialSwitch == true).ToList<FIFPAppointment>();
            //Plans.SelectMany(s => s.LsdPlans).Where(p => p.IsRadialSwitch == true).ToList<FIFPAppointment>().RemoveAll();
            List<FIFPAppointment> afterDelete = Plans.SelectMany(s => s.LsdPlans).Where(p => p.IsRadialSwitch == true).ToList<FIFPAppointment>();
            foreach (FIFPAppointment plan in Plans)
            {
                foreach (RadialSwitch rsAppointment in radialSwitchList)
                {
                    bool overlap = !(plan.End < rsAppointment.StartDate || plan.Start > rsAppointment.EndDate);
                    if (overlap)
                    {
                        DateTime startDate = new DateTime();
                        DateTime endDate = new DateTime();
                        if (plan.Start > rsAppointment.StartDate)
                            startDate = plan.Start;
                        else
                            startDate = rsAppointment.StartDate;

                        if (plan.End < rsAppointment.EndDate)
                            endDate = plan.End;
                        else
                            endDate = rsAppointment.EndDate;

                        if (ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.UnitType == FIFPConstants.UNITTYPE_PLATFORM)//OCCP
                        {
                            if (ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Contains(rsAppointment.UnitId))
                                ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Remove(rsAppointment.UnitId);
                        }
                        else
                        {
                            ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Add(rsAppointment.UnitId);
                        }
                        Unit radialUnit = UnitNameList.Where(s => s.UnitID == rsAppointment.UnitId).FirstOrDefault();
                        FIFPAppointment lsdAppointment = new FIFPAppointment() { UnitID = rsAppointment.UnitId, UnitName = radialUnit.UnitName, LSDParentActivityPlanId = ServiceLocator.Get<ShutdownMngVM>().SelectedActivity.PlanID, UnitType = radialUnit.UnitType, Start = startDate, OriginalStart = rsAppointment.StartDate, End = endDate, OriginalEnd = rsAppointment.EndDate, FluidType = radialUnit.FluidType, IsAppointmentDelete = true, IsLinkedShutdownPlan = true, UnitStatus = "C", Division = plan.Division, ParentActivityCode = plan.ActivityCode, IsRadialSwitch = true, LsdReason = appointment.LsdReason };
                        plan.LsdPlans.Add(lsdAppointment);
                        GetLSDPlans(UnitNameList.Where(p => p.UnitID == rsAppointment.UnitId).SelectMany(s => s.ChildUnitList).ToList<Unit>(), lsdAppointment, plan);
                    }
                }
            }
        }

        private List<RadialSwitch> MergeRadialDBWithTempList()
        {
            List<RadialSwitch> tempList = new List<RadialSwitch>();
            if (ServiceLocator.Get<ImportVM>().RadialSwitchListFromDB != null && ServiceLocator.Get<ImportVM>().RadialSwitchListFromDB.Count > 0)
                tempList.AddRange(ServiceLocator.Get<ImportVM>().RadialSwitchListFromDB);
            if (RadialSwitchList != null && RadialSwitchList.Count > 0)
                tempList.AddRange(RadialSwitchList.Where(s => s.IsRevert == false));
            //foreach (RadialSwitch rs in RadialSwitchList)
            //{
            //    if (rs.IsRevert == true)
            //    {
            //        RadialSwitch radialSwitch = tempList.Where(s => s.UnitId == rs.UnitId && s.StartDate == rs.StartDate && s.EndDate == rs.EndDate).FirstOrDefault();
            //        if (radialSwitch != null)
            //            tempList.Remove(radialSwitch);
            //    }
            //}
            return tempList;
        }

        #region Generate Linked shutdowns
        private void GetLSDPlans(List<Unit> lstUnits, FIFPAppointment appointment, FIFPAppointment plan)
        {
            foreach (Unit unit in lstUnits)
            {
                plan.LsdPlans.Add(new FIFPAppointment() { UnitID = unit.UnitID, UnitName = unit.UnitName, UnitType = unit.UnitType, Start = appointment.Start, End = appointment.End, OriginalStart = appointment.OriginalStart, OriginalEnd = appointment.OriginalEnd, FluidType = appointment.FluidType, IsAppointmentDelete = true, IsLinkedShutdownPlan = true, UnitStatus = "C", Division = appointment.Division, ParentActivityCode = plan.ActivityCode, IsRadialSwitch = true });
                this.GetLSDPlans(UnitNameList.Where(p => p.ParentUnitID == unit.UnitID).ToList<Unit>(), appointment, plan);
            }
        }
        #endregion

        #region Get ChildUnitList

        private void GetChildUnitNameList(List<Unit> lstUnits)
        {
            foreach (Unit unit in lstUnits)
            {
                ChildUnitList.Add(unit.UnitID);
                GetChildUnitNameList(UnitNameList.Where(p => p.ParentUnitID == unit.UnitID).ToList());
            }
        }

        private void GetChildUnitNameList(List<Unit> lstUnits, bool bInitial)
        {
            if (bInitial)
            {
                bInitial = false;
                if (lstUnits.Count > 0)
                    ChildUnitList.Add(lstUnits[0].UnitID);
            }
            else
            {
                foreach (Unit unit in lstUnits)
                    ChildUnitList.Add(unit.UnitID);
            }
            foreach (Unit unit in lstUnits)
            {
                GetChildUnitNameList(UnitNameList.Where(p => p.ParentUnitID == unit.UnitID).ToList(), bInitial);
            }
        }
        #endregion

        private void AppointmentSelectionChanged(RadScheduleView view)
        {
            if ((ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked) && ServiceLocator.Get<ShutdownMngVM>().SelectedLSDLocation != null && view.SelectedAppointment != null)
            {
                FIFPAppointment appointment = view.SelectedAppointment as FIFPAppointment;
                if (appointment != null && ServiceLocator.Get<ShutdownMngVM>().ActivityListWithSelectedUnit.Contains(appointment))
                    ServiceLocator.Get<ShutdownMngVM>().SelectedActivity = appointment;
            }
        }

        private void ShowPopup(string title, string message)
        {
            Warning warningWindow = new Warning();
            warningWindow.CancelButton.Visibility = Visibility.Collapsed;
            warningWindow.Title = string.Format(title);
            warningWindow.lblMessage.Text = string.Format(message);
            warningWindow.lblMessage.Visibility = Visibility.Visible;
            warningWindow.Show();
            warningWindow.OKButton.Click += (o, e1) =>
            {
                warningWindow.lblMessage.Visibility = Visibility.Collapsed;
            };
        }

        #endregion
    }
}
